package com.zhoyq.project.exception;

import javax.servlet.http.HttpServletRequest;

import com.zhoyq.project.common.model._ReturnKit;
import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

public class ExceptionInterceptor implements Interceptor {

  @Override
  public void intercept(Invocation inv) {
    try{
      inv.invoke();
    }catch(Exception e){
      Controller controller = inv.getController();
      HttpServletRequest req = controller.getRequest();
      boolean isAjax = false;
      isAjax = "XMLHttpRequest".equalsIgnoreCase(
          req.getHeader("X-Requested-With"));
      if(!isAjax) isAjax = StringUtils.isEmpty(controller.getPara("_ajax"));
      if(isAjax){
        controller.renderJson(_ReturnKit.get(false, e.getMessage()));
      }else{
        controller.setAttr("msg", e.getMessage());
        controller.render("/error.html");
      }
    }
  }
}
